package com.forum.module.system.service.feedback;

import com.alibaba.nacos.shaded.com.google.common.annotations.VisibleForTesting;
import com.forum.framework.common.exception.util.ServiceExceptionUtils;
import com.forum.framework.common.pojo.PageResult;
import com.forum.framework.common.util.object.BeanUtils;
import com.forum.framework.security.core.util.SecurityUtils;
import com.forum.module.system.controller.admin.feedback.vo.FeedBackPageReqVO;
import com.forum.module.system.controller.admin.feedback.vo.FeedBackSavaReqVO;
import com.forum.module.system.dal.dataobject.feedback.FeedBackDO;
import com.forum.module.system.dal.mysql.feedback.FeedBackMapper;
import org.springframework.stereotype.Service;

import static com.forum.module.system.enums.ErrorCodeConstants.FEEDBACK_NOT_EXISTS;

/**
 * 功能:
 * 作者:ouyzh
 * 日期:2025/3/19 21:10
 */
@Service
public class FeedBackServiceImpl implements FeedBackService {
    private final FeedBackMapper feedBackMapper;

    public FeedBackServiceImpl(FeedBackMapper feedBackMapper) {
        this.feedBackMapper = feedBackMapper;
    }

    @Override
    public Long createFeedBack(FeedBackSavaReqVO reqVO) {
        FeedBackDO feedBackDO = BeanUtils.toBean(reqVO, FeedBackDO.class);

        feedBackDO.setUserId(SecurityUtils.getLoginUserId());
        feedBackDO.setStatus(0);

        feedBackMapper.insert(feedBackDO);
        return feedBackDO.getId();
    }

    @Override
    public void updateFeedBack(FeedBackSavaReqVO reqVO) {
        FeedBackDO feedBackDO = BeanUtils.toBean(reqVO, FeedBackDO.class);

        feedBackMapper.updateById(feedBackDO);
    }

    @Override
    public PageResult<FeedBackDO> getFeedBackPage(FeedBackPageReqVO pageReqVO) {
        return feedBackMapper.selectPage(pageReqVO);
    }

    @Override
    public void deleteById(Long id) {
        // 1. 校验反馈存在
        validateFeedBackExists(id);

        feedBackMapper.deleteById(id);
    }

    @VisibleForTesting
    FeedBackDO validateFeedBackExists(Long id) {
        if (id == null) {
            return null;
        }
        FeedBackDO feedBackDO = feedBackMapper.selectById(id);
        if (feedBackDO == null) {
            throw ServiceExceptionUtils.exception(FEEDBACK_NOT_EXISTS);
        }
        return feedBackDO;
    }
}
